<template>
  <div class="login_container">
    <CommonBack :title="title"></CommonBack>
    <div class="login_box">
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >登录</van-button
          >
        </div>
      </van-form>
      <div class="bottom">
        <router-link to="/register">注册账号</router-link> 
        <a href="javascript:;">忘记密码</a>
      </div>
    </div>
  </div>
</template>

<script>
import CommonBack from "@/components/CommonBack.vue";
import { Toast } from 'vant';
import Cookies from 'js-cookie';
export default {
  name: "Login",
  data() {
    return {
      title: "登录",
      username: "",
      password: "",
    };
  },
  methods: {
    firstCreate() {
      this.$store.commit("changeTabShow");
    },
    onSubmit(values) {
      // 判断是否存在当前这个 Cookies
      if(!Cookies.get(`${values.username}`)){
        Toast.fail('你还没有注册,请先注册')
        return
      }
      // 拿去注册的token
      let obj = JSON.parse(Cookies.get(`${values.username}`))
      // 判断密码是否正确
      if( values.password === obj.password){
        Toast.success('登录成功')
        sessionStorage.setItem('token' , JSON.stringify(obj.token))
        sessionStorage.setItem('username' , JSON.stringify(obj.username))
        setTimeout(() => {
          this.$router.push({
            path:'/home'
          })
          Toast.clear()
        } , 1000)
      }
      else{
        Toast.fail('密码不正确,请重新输入')
      }
    },
  },
  created() {
    this.firstCreate();
  },
  destroyed() {
    this.$store.commit("changeTabShow");
  },
  components: { CommonBack },
};
</script>

<style lang="less" scoped>
.login_container {
  padding-top: 46px;
  /deep/ .van-cell {
    position: relative;
    margin: 15px 0px;
    overflow: visible;
    &::after {
      bottom: 8px;
    }
    .van-field__error-message {
      position: absolute;
      left: 0px;
      bottom: -25px;
    }

    .van-field__control{
      background-color: #fff;
    }
  }
  .login_box {
    margin-top: 1.4648rem;
    width: 100vw;
    .bottom{
      padding: 0px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      a{
        font-size: 12px;
        color: 	#B7B7B7;
      }
    }
  }
}
</style>